/**
 * Created with Vim7.3 ubuntu12.04
 * @fileOverview : 
 * @author : Lyle <lylechen2014@gmial.com>
 * @since : 2014-09-30 11:02:27
 * @filename : static/logic/nmm/src/views/editProfile2.js
 * @version : 
 * @description : 
 */

define(function(require, exports, module){
    require("{component}dialog/zepto.dialog.css");
    require('{component}promptTip/promptTip.css');

    var editProfileView,userObj,
        mId = 'editProfile',reRender = false,menuName = 'editProfile',
        imglazyload = require('{component}imglazyload/zepto.imglazyload'),
        panel = require('{component}panel/zepto.panel'),
        upload  = require('{component}upload/upload'),
        dialog = require('{component}dialog/zepto.dialog'),
        promptTip = require('{component}promptTip/promptTip'),
        tpl = require('{view}editProfile.tpl'),
        tplC  = require('{view}countryList.tpl'),
        tplS  = require('{view}stateList.tpl');
        tplI  = require('{view}incomeList.tpl');
        tplN = require('{view}userNav.tpl');

    editProfileView = Backbone.View.extend({

        template: _.template(tpl),
        templateN: _.template(tplN),
        templateC: _.template(tplC),
        templateS: _.template(tplS),
        templateI: _.template(tplI),

        render: function (obj) {
            if (!share.checkPermission(true)){return;}; 
            share.reRender(reRender,mId);
 
            userObj = share.getObjStorage(share.userInfo().usr_id);

            if ($('#'+mId).length < 1) {
                $('body').append(this.template(userObj));
                $('#'+mId).find('.mainPhoto').imglazyload({startY : 0,endY: $(window).height(),sW:45,sH:45}); 
                this.bindEvt(); 
                this.initUpload(); 
            } else {
                $('#'+mId).css('display','block');
            }

            share.panel(panel,this.templateN,mId,menuName);
            this.setUpload();
            this.initCountryList();        
            var date = util.FormatDate(userObj.detail.basics.age_year,userObj.detail.basics.age_month,userObj.detail.basics.age_day);

            $('#'+mId).find('#age').val(date); 
            $('#'+mId).find('#zip').val(userObj.account.zip); 
            this.setphoto();
        },

        setphoto : function() {
            var url,
                userObj = share.getObjStorage(share.userInfo().usr_id);
            if (userObj.photo!= null) {
                url = userObj.photo.picture;
            } else {
                url = userObj.defaultImg;
            } 

            //$('#'+mId).find('.mainPhoto').find('img').attr('src',url);
            $('#'+mId).find('.mainPhoto').find('img').replaceWith('<img class="imglazyload" src url='+url+' />');                         
            $('#'+mId).find('.mainPhoto').imglazyload({startY : 0, endY: $(window).height(),sW:45,sH:45});
        },

        bindEvt : function() {
            var tthis = this,dom = $('#'+mId); 
            
            dom.find('.back').on('tap',function(e){
                window.location.href = '#myProfile/whole'; 
            });
      
            $('#editProfile .country').live('change.editProflie',function(){
                var val = $(this).find('option:selected').val();
                tthis.initStateList(val);
                dom.find('#zip').val('');
            });

            dom.find('.save').on('tap',function(e){
                var value = dom.find('.headline').val(),
                    age = share.ages(dom.find('#age').val());

                share.blur('editProfile'); 

                if(value == '') { 
                   promptTip.show({type:'error',text:'This profile headline is required!', dom:dom.find('.promptTip'),time:3000});
                   return;
                }

                if (age < 18 || age > 99) {
                    promptTip.show({type:'error',text:'This Birthday is must be 18-99 age.', dom:dom.find('.promptTip'),time:3000});
                } else if (value.length > 60) {
                    promptTip.show({type:'error',text:'60 characters maximum.', dom:dom.find('.promptTip'),time:3000});
                } else {
                    var usr_id = userObj.account.usr_id,
                          date = new Date(dom.find('#age').val()),
                         r_zip = dom.find('#zip').val(),
                     r_country = dom.find('#country').val(),
                r_country_name = dom.find('#country').find('option:selected').html(),
                     r_state   = dom.find('#state').val(),                   
                r_state_name   = dom.find('#state').find('option:selected').html(),              
                      r_city   = dom.find('#city').val();                   
                       
                    var obj = {
                            title : value,
                         age_year : date.getFullYear(), 
                        age_month : date.getMonth() + 1,
                          age_day : date.getDate(),
                            r_zip : r_zip
                    };

                    if (r_country !== null && r_country !== undefined) {obj.r_country = r_country};
                    if (r_state !== null && r_state !== undefined) {obj.r_state_id = r_state};
                    if (r_city !== null && r_city !== undefined) {obj.r_city = r_city};
                     
                    var callback = function(data){
                        userObj.about.headline = obj.title;
                        userObj.detail.basics.age_day = obj.age_day;
                        userObj.detail.basics.age_month = obj.age_month;
                        userObj.detail.basics.age_year = obj.age_year;
                        userObj.account.zip = r_zip;
                        userObj.account.age = share.age(obj.age_year);
                     
                        if (r_country !== null) {
                            userObj.account.country = r_country;
                            userObj.account.country_name = r_country_name;
                        };

                        userObj.account.state = (r_state == null) ? '' : r_state;
                        userObj.account.state_name = (r_state == null) ? '' : r_state_name; 
                        if (data.data !== null && data.data !== undefined) {
                            userObj.account.city = (data.data.r_city == null || data.data.r_city == undefined) ? '' : data.data.r_city;
                        }

                        share.cacheUserInfo(usr_id,userObj);
                        share.cacheUserInfo('ms_user_info', {
                            'age_day'   : obj.age_day,
                            'age_month' : obj.age_month,
                            'age_year'  : obj.age_year,
                            'zip'       : obj.zip,
                            'state'     : r_state,
                            'country'   : r_country,
                            'state_name': r_state_name,
                            'country_name': r_country_name,
                        });
                        panel.renderUserInfo();
                        window.location.href = '#myProfile/whole'; 
                    }
                   
                    share.updateProfile(usr_id,callback,obj);
                }   
            });

        },

        initCountryList : function() {
            share.getCountryList({callback:this.renderCountryDom,that:this}); 
        },

        renderCountryDom : function(data,obj) {
            $('#'+mId).find('.country').html(obj.that.templateC({ arr: data.data, val: userObj.account.country}));
            obj.that.initStateList(userObj.account.country);
        },

        
        initStateList : function(val) {
            var val = parseInt(val);
            if (val !== 0 && val !== 31 && val !== 180) {
                share.getStateList({callback:this.renderStateDom,that:this,country:val}); 
                this.initCityInput();
            } else {
                var stateObj = $('#'+mId).find('.state');
                stateObj.html('');
                this.clearCityInput();
            };
        },

        clearState : function() {
            var stateobj = $('#'+mId).find('.state');
            if (stateobj !== undefined) {
                stateobj.html('');
             }
        },

        renderStateDom : function(data,obj) {
            if (data.data.length > 0 ) {
               $('#'+mId).find('.state').html(obj.that.templateS({ arr: data.data,val:userObj.account.state}));
            } else {
               this.that.clearState();                       
            }
        },
      
        initCityInput : function() {
            $('#'+mId).find('.city').html('<label> city </label><input id="city" value ="'+((userObj.account.city) ? userObj.account.city : '')+'"></input>').addClass('city_class');    
        },

        clearCityInput : function() {
            $('#'+mId).find('.city').html('').removeClass('city_class');    
        },

        uploadOpt : function() {
             var tthis = this, 
                 obj =   {
                    id : 'uploadMainPhoto',
                    filter: 'image',
                    maxsize: 2048000,
                    url: seajs.data.vars.apiAccessUrl + 'upload_main_photo',
                    onSuccess: function(data) {
                        $('#'+mId).find('.uploading').hide();
                       //try {
                            var data = JSON.parse(data);
                            if (data.errcode !== undefined) {
                                dialog.open({
                                    type    : 'contentDialog',
                                    dom     : $('#'+mId),
                                    content : data.errmsg
                                });
                            } else {                          
                              var usr_id = userObj.account.usr_id;
                              userObj.pictures.unshift(data.picture);   
                              share.cacheUserInfo(usr_id,userObj);
                              share.updateMainPhoto(usr_id);
                              tthis.setphoto();
                            }
                        //} catch(err){};

                    },
                    onError: function(data){console.log(data)},
                    onProgress: function(evt){
                    },
                    onReader: function(evt) { 
                        $('#'+mId).find('.uploading').show();
                    }
                };
                
                return obj;
        },

        initUpload : function() {
                upload.init(this.uploadOpt());
        },

        setUpload : function() {
                upload.setUploadOpt(this.uploadOpt()); 
        }
	});
	module.exports = editProfileView;
})

